package com.itlaoqi.mcp.server.weather.service;

import com.itlaoqi.mcp.server.weather.bean.FileReadRequest;
import com.itlaoqi.mcp.server.weather.bean.FileReadResponse;
import com.itlaoqi.mcp.server.weather.bean.FileWriteRequest;
import com.itlaoqi.mcp.server.weather.bean.FileWriteResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@Slf4j
@Service
public class LocalFileService {
    @Tool(description = "写入本地文件，自动创建目录和文件")
    public FileWriteResponse writeLocalFile(FileWriteRequest request) {
        String filePath = request.getFilePath();
        Path path = Paths.get(filePath);
        Path dirPath = path.getParent();

        // 创建目录（如果不存在）
        if (dirPath != null) {
            try {
                Files.createDirectories(dirPath);
            } catch (IOException e) {
                log.error("创建目录[{}]失败", dirPath, e);
                FileWriteResponse fileResponse = new FileWriteResponse();
                fileResponse.setResult("创建目录失败: " + e.getMessage());
            }
        }

        // 写入文件内容
        try {
            Files.write(path, request.getContent().getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            return FileWriteResponse.builder().result("success").build();
        } catch (IOException e) {
            log.error("写入文件[{}]失败", filePath, e);
            return FileWriteResponse.builder().result("写入文件失败: " + e.getMessage()).build();
        }
    }
    @Tool(description = "读取本地文件内容")
    public FileReadResponse readLocalFile(FileReadRequest request) {
        String filePath = request.getFilePath();
        Path path = Paths.get(filePath);

        // 检查文件是否存在
        if (!Files.exists(path)) {
            return FileReadResponse.builder().result("文件不存在").build();
        }

        try {
            // 读取文件内容
            String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
            return FileReadResponse.builder()
                    .result("success")
                    .content(content) // 假设FileWriteResponse有content字段
                    .build();
        } catch (IOException e) {
            log.error("读取文件[{}]失败", filePath, e);
            return FileReadResponse.builder()
                    .result("读取失败: " + e.getMessage())
                    .build();
        }
    }
}
